package com.langsin.crmpro.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.langsin.crmpro.base.BaseDao;
import com.langsin.crmpro.model.User;

public class UserDAOImpl extends BaseDao implements UserDAO {
	
	public static final String USERNAME = "username";
	public static final String PASSWORD = "password";

	public List<User> query(String sql, Object[] values) {
		return this.getHibernateTemplate().find(sql, values);
	}

	public void save(User user) {
		this.getHibernateTemplate().save(user);
	}

	public List findByUsername(Object username) {
		return findByProperty(USERNAME, username);
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding User instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from User as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public Boolean checkUser(String userName, String userPwd) {
		String queryString = "from User as u where u.username=? and u.password=?";
		Query queryObject = getSession().createQuery(queryString);
		int i = 0;
		queryObject.setParameter(i++, userName);
		queryObject.setParameter(i++, userPwd);
		int num = queryObject.list().size();
		if(num == 1){
			return true;
		}else{
			return false;
		}
	}

}
